package com.niit.utils;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送，仅支持SMTP服务器
 * 
 * @author Jarvan
 */
public class MailUtil {

	private Properties props; // 系统属性
	private Session session; // 邮件会话对象
	private MimeMessage mimeMsg; // MIME邮件对象
	private Transport transport = null;

	/**
	 * 发送不带附件的邮件
	 * 
	 * @param from
	 *            发信人
	 * @param to
	 *            收信人
	 * @param subject
	 *            主题
	 * @param content
	 *            邮件内容
	 */
	public void send(String from, String password, String to, String subject,
			String content) {
		session = getSession(from);
		mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
		try {
			mimeMsg.setFrom(new InternetAddress(from));// 设置发件人
			mimeMsg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to));// 设置收件人
			mimeMsg.setSubject(subject);// 设置邮件主题
			mimeMsg.setText(content); // 设置邮件的内容文本
			transport = session.getTransport("smtp");
			transport.connect(getSmtp(from), from, password); // 连接发信服务器
			transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				transport.close();
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 获取邮件回话对象
	 * @param from 发件人邮箱
	 * @return
	 */
	private Session getSession(String from) {
		if (props == null)
			props = System.getProperties(); // 获得系统属性对象
		props.put("mail.smtp.host", getSmtp(from)); // 设置SMTP主机
		props.put("mail.smtp.auth", "true");// 设置是否需要身份验证
		return Session.getDefaultInstance(props, null); // 获得邮件会话对象
	}
	
	/**
	 * 获取smtp邮件服务器地址
	 * @param from 发件人邮箱
	 * @return
	 */
	private String getSmtp(String from){
		return "smtp."+from.split("\\@")[1];
	}

	/**
	 * 不发邮件，验证邮箱的用户名密码是否正确
	 * 
	 * @param from
	 *            发送人的邮箱
	 * @param password
	 *            发送人的邮箱密码
	 * @return
	 */
	public boolean isCorrectMail(String from, String password) {
		boolean flag = false;
		session = getSession(from);
		try {
			transport = session.getTransport("smtp");
			transport.connect(from, password);
			flag = transport.isConnected();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				transport.close();
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
		return flag;
	}
	
	public boolean isCorrectMail(String email){
		String reg = "\\w+@\\w+(\\.\\w+)+";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(email);
		if(m.find()){
			return true;
		}else{
			return false;
		}
	}
}
